#!/usr/bin/env python3
"""
初始化 MinIO Bucket
"""
import sys
import os

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from minio import Minio
from minio.error import S3Error
import json
from app.core.config import settings
from loguru import logger

def init_minio_bucket():
    """初始化 MinIO Bucket"""
    try:
        # 创建 MinIO 客户端
        client = Minio(
            endpoint=settings.MINIO_ENDPOINT,
            access_key=settings.MINIO_ACCESS_KEY,
            secret_key=settings.MINIO_SECRET_KEY,
            secure=settings.MINIO_SECURE
        )
        
        bucket_name = settings.MINIO_BUCKET
        
        # 检查 bucket 是否存在
        if client.bucket_exists(bucket_name):
            logger.info(f"✅ Bucket '{bucket_name}' 已存在")
        else:
            # 创建 bucket
            client.make_bucket(bucket_name)
            logger.success(f"✅ Bucket '{bucket_name}' 创建成功")
        
        # 设置 bucket 为公开访问
        policy = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"AWS": "*"},
                    "Action": ["s3:GetObject"],
                    "Resource": [f"arn:aws:s3:::{bucket_name}/*"]
                }
            ]
        }
        
        client.set_bucket_policy(bucket_name, json.dumps(policy))
        logger.success(f"✅ Bucket '{bucket_name}' 已设置为公开访问")
        
        # 列出所有 buckets
        buckets = client.list_buckets()
        logger.info("📦 当前所有 buckets:")
        for bucket in buckets:
            logger.info(f"   - {bucket.name}")
        
        return True
        
    except S3Error as e:
        logger.error(f"❌ MinIO 错误: {e}")
        return False
    except Exception as e:
        logger.error(f"❌ 初始化失败: {e}")
        return False

if __name__ == "__main__":
    logger.info("🚀 开始初始化 MinIO Bucket...")
    logger.info(f"📝 配置信息:")
    logger.info(f"   - Endpoint: {settings.MINIO_ENDPOINT}")
    logger.info(f"   - Bucket: {settings.MINIO_BUCKET}")
    logger.info(f"   - Secure: {settings.MINIO_SECURE}")
    
    success = init_minio_bucket()
    
    if success:
        logger.success("🎉 MinIO 初始化完成！")
        sys.exit(0)
    else:
        logger.error("❌ MinIO 初始化失败！")
        sys.exit(1)

